<?php

namespace app\common\model;

use think\Model;
use think\Db;

class LiquorOrder extends Model
{
    protected $insert = ['ctime'];
    
    protected function setCtimeAttr()
    {
        return time();
    }
    
    public function user()
    {
        return $this->hasOne('User', 'id', 'user_id')->field(['id', 'avatar', 'nickname', 'password', 'mobile']);
    }
    
    public function liquor()
    {
        return $this->hasOne('Liquor', 'id', 'liquor_id');
    }
    /**
     * 取消取酒单操作
     * @param type $id
     * @param type $user_id
     * @return type
     */
    public function cancel($id, $user_id=0)
    {
        $liquor_info = $this->get($id);
        //用户取消处理
        if($user_id){
            if($user_id != $liquor_info->user_id) {
                return [
                    'status'    =>  false,
                    'msg'       =>  '取消失败'
                ];
            }
            if($liquor_info->status == '1'){
                return [
                    'status'    =>  false,
                    'msg'       =>  '已出单无法取消'
                ];
            }
        }
        
        if($liquor_info->status == '2') {
            return [
                'status' => false,
                'msg'   => '无法重复取消'
            ];
        }
        $liquor_model = new Liquor();
        $info = $liquor_model->get($liquor_info->liquor_id);
        if($info->status == 'expire') {
            return [
                'status' => false,
                'msg'   => '存酒已过期无法取消'
            ];
        }        
        Db::startTrans();
        $liquor['number'] = $info->number + $liquor_info->number;
        $liquor['status'] = 'deposit';
        if($liquor_model->save($liquor, ['id' => $info->id])) {
            $liquor_info->status = 2;
            if(!$liquor_info->save()) {
                Db::rollback();
                return [
                    'status' => false,
                    'msg'   => '订单更新失败'
                ];
            }
            Db::commit();
            return [
                'status' => true,
                'msg'   => '取消成功'
            ];
        }
        return [
            'status' => false,
            'msg'   => '订单更新失败'
        ];
    }
}
